package cn.anosi.utils;

import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;

import cn.anosi.page.PageResponseBean;
import cn.anosi.page.Pager;

/**
 * 分页工具
 * @author admin
 *
 */
public class PageUtils {
	private static final int PAGE_NUM = 0;
	private static final int PAGE_SIZE = 10;
	
	/**
	 * 获取分页排序对象
	 * @param pager
	 * @return
	 */
	public static Pageable getPageable(Pager pager){
		if(null == pager){
			return new PageRequest(PAGE_NUM, PAGE_SIZE);
		}else{
			if(ObjectsUtils.notNull(pager.getPageNum(), pager.getPageSize())){
				if(ObjectsUtils.notNull(pager.getProperty(), pager.getDirection())){
					return new PageRequest(pager.getPageNum(), pager.getPageSize(), pager.getDirection(), pager.getProperty());
				}else{
					return new PageRequest(pager.getPageNum(), pager.getPageSize());
				}
			}else{
				if(ObjectsUtils.notNull(pager.getProperty(), pager.getDirection())){
					return new PageRequest(PAGE_NUM, PAGE_SIZE, pager.getDirection(), pager.getProperty());
				}else{
					return new PageRequest(PAGE_NUM, PAGE_SIZE);
				}
			}
		}
	}
	
	/**
	 * 将数据设置到分页对象中
	 * @param datas
	 * @param pager
	 * @return
	 */
	public static <T> PageResponseBean<T> getPageResponseBean(Page<T> datas, Pager pager){
		if(ObjectsUtils.notNull(datas)){
			if(pager == null){
				pager = new Pager();
				pager.setDraw(1);
			}
			
			PageResponseBean<T> pageResponseBean = new PageResponseBean<>();
			pageResponseBean.setData(datas.getContent());
			pageResponseBean.setDraw(pager.getDraw() + 1);
			pageResponseBean.setRecordsTotal(datas.getTotalElements());
			pageResponseBean.setRecordsFiltered(datas.getTotalElements());
			return pageResponseBean;
		}else{
			return new PageResponseBean<T>();
		}
	}
}
